package ATM;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Scanner;

public class ATM {

    public static final int MAX_CASH = 200000;

    private int cash = 100000;

    private HashMap<String, UserInfo> allUsers; //把allUsers的类型修改为Map

    private UserInfo theUser;//当前登陆对象

    public ATM() {
/*        File file = new File("user.data");
        if (!file.exists()) {
            allUsers = new HashMap<>();

            UserInfo user1 = new UserInfo("zhang3", "123456", 10000);
            UserInfo user2 = new UserInfo("li4", "123456", 10000);
            UserInfo user3 = new UserInfo("wang5", "123456", 10000);
            UserInfo user4 = new UserInfo("zhao6", "123456", 10000);

            allUsers.put("zhang3", user1);
            allUsers.put("li4", user2);
            allUsers.put("wang5", user3);
            allUsers.put("zhao6", user4);
            return;
        }*/

        this.allUsers = FileOperation.readFile();
    }

    public void run() {
        this.welcome();
        boolean flag = this.login();
        if (flag) {
            while (true) {
                String choice = this.chooseMenu();
                switch (choice) {
                    case "1":
                        this.query();
                        break;
                    case "2":
                        this.getMoney();
                        break;
                    case "3":
                        this.saveMoney();
                        break;
                    case "4":
                        this.trans();
                        break;
                    case "5":
                        this.modPwd();
                        break;
                    case "6":
                        this.exit();
                        break;
                    default:
                        System.out.println("没有该选项，请重新选择。");
                }
            }
        } else {
            System.out.println("三次机会用完，你的卡被吞。");
            System.out.println("请在三日内带有效证件到柜台处理。");
        }

    }

    private void welcome() {
        System.out.println("欢迎使用ICBC银行ATM");
    }

    private boolean login() {
        for (int i = 0; i < 3; i++) {
            Scanner scan = new Scanner(System.in);
            System.out.println("请输入用户名:");
            String inputname = scan.next();
            System.out.println("请输入密码：");
            String inputPwd = scan.next();

/*            for(UserInfo user : allUsers){
                if(user.getUsername().equals(inputname) &&
                    user.getPassword().equals(inputPwd)){
                    this.theUser = user;
                    return true;
                }
            }*/
            if (allUsers.containsKey(inputname)) {
                UserInfo userInfo = allUsers.get(inputname);
                if (userInfo.getPassword().equals(inputPwd)) {
                    System.out.println("登陆成功");
                    this.theUser = userInfo;
                    return true;
                }
            }
            System.out.println("用户名/密码有误，还有" + (2 - i) + "次机会。");
        }
        return false;
    }

    private String chooseMenu() {
        System.out.println("请选择你要执行的操作：");
        System.out.println("1、查询余额；2、取款；3、存款；4、转账；5、修改密码；6、退出");
        Scanner scan = new Scanner(System.in);
        String choice = scan.next();
        return choice;
    }

    private void query() {
        System.out.println("你当前的余额是：" + this.theUser.getAccount() + "元");
    }

    private void getMoney() {
        //1、输入用户的取款金额
        Scanner scan = new Scanner(System.in);
        int inputMoney = 0;
        do {
            System.out.println("请输入你要取款的金额：");
            try {
                inputMoney = scan.nextInt();
                break;
            } catch (InputMismatchException inputMismatchException) {
                System.out.println("取款金额必须是小于20000元的百元整钞。");
                System.out.println("是否重新输入取款金额？Y/N");
                String yesOrNot = scan.next();
                if (yesOrNot.equalsIgnoreCase("N")) {
                    return;
                }
            }
        } while (true);


        //2、校验金额的有效性
        //负数\百元\单笔不能超过20000\不能多于余额\不能多于现金
        if (inputMoney <= 0) {
            System.out.println("只能输入非负数金额");
            return;
        }
        if (inputMoney % 100 != 0) {
            System.out.println("只接受百元整钞");
            return;
        }
        if (inputMoney > 20000) {
            System.out.println("单笔操作不能超过2万");
            return;
        }
        if (inputMoney > theUser.getAccount()) {
            System.out.println("您当前的余额不足");
            return;
        }
        if (inputMoney > cash) {
            System.out.println("本机现金不足");
            return;
        }
        //3、修改用户余额值
        this.theUser.setAccount(this.theUser.getAccount() - inputMoney);
        //4、修改ATM现金值
        this.cash -= inputMoney;
        //5、相应的通知信息
        FileOperation.writeFile(this.allUsers);
        System.out.println("操作成功，取款" + inputMoney + "元。");
    }

    private void saveMoney() {
        //1、输入用户的存款金额
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入你要存款的金额：");
        int inputMoney = scan.nextInt();
        //2、校验金额的有效性
        //负数\百元\单笔不能超过20000\不能多于现金上限
        if (inputMoney <= 0) {
            System.out.println("只能输入非负数金额");
            return;
        }
        if (inputMoney % 100 != 0) {
            System.out.println("只接受百元整钞");
            return;
        }
        if (inputMoney > 20000) {
            System.out.println("单笔操作不能超过2万");
            return;
        }
        if (inputMoney + cash > MAX_CASH) {
            System.out.println("本机容量不足");
            return;
        }
        //3、修改用户余额值
        this.theUser.setAccount(this.theUser.getAccount() + inputMoney);
        //4、修改ATM现金值
        this.cash += inputMoney;
        //5、相应的通知信息
        FileOperation.writeFile(this.allUsers);
        System.out.println("操作成功，存款" + inputMoney + "元。");
    }

    private void trans() {
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入对方账号：");
        String toUsername = scan.next();
        UserInfo toUser = null;
/*        for(UserInfo user : this.allUsers){
            if(user.getUsername().equals(toUsername)){
                toUser = user;
                break;
            }
        }*/
        if (allUsers.containsKey(toUsername) && !toUsername.equals(theUser.getUsername())) {
            UserInfo userInfo = allUsers.get(toUsername);
            toUser = userInfo;
        }

        if (toUser == null) {
            System.out.println("你输入的用户不存在。");
            return;
        }

        System.out.println("请输入你要转账的金额：");
        double inputMoney = scan.nextDouble();
        if (inputMoney <= 0) {
            System.out.println("只能输入非负数金额");
            return;
        }
        if (inputMoney > this.theUser.getAccount()) {
            System.out.println("您当前的余额不足");
            return;
        }
        this.theUser.setAccount(this.theUser.getAccount() - inputMoney);
        toUser.setAccount(toUser.getAccount() + inputMoney);
        FileOperation.writeFile(this.allUsers);
        System.out.println("转账操作成功。");

        //临时增加的作业
        //1.时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        LocalDate localDate = LocalDate.now();
        String description = localDate.format(formatter);
        //System.out.println(description);

        //2.I/O文本 写入
        String msg = "";
        String name = "";
        FileWriter fw = null;
        name = this.theUser.getUsername() + "to" + toUser.getUsername() + ".txt";
        try {
            fw = new FileWriter(name);
            msg = description + "," + this.theUser.getUsername() + "向" + toUser.getUsername() + "转账" + inputMoney + "元";
            fw.write(msg);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //2.I/O文本 读出
        FileReader fr = null;
        String str = "";
        try {
            fr = new FileReader(name);
            int b = 0;
            while ((b = fr.read()) != -1) {
                str += (char) b;
            }
            System.out.println(str);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private void modPwd() {
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入你的当前密码：");
        String oldPwd = scan.next();
        System.out.println("请输入你的新密码：");
        String newPwd = scan.next();
        System.out.println("请再次输入你的新密码：");
        String newPwd2 = scan.next();

        if (!oldPwd.equals(theUser.getPassword())) {
            System.out.println("当前密码有误");
            return;
        }
        if (oldPwd.equals(newPwd)) {
            System.out.println("新旧密码完全相同");
            return;
        }
        if (!newPwd.equals(newPwd2)) {
            System.out.println("两次新密码不一致");
            return;
        }
        this.theUser.setPassword(newPwd);
        FileOperation.writeFile(this.allUsers);
        System.out.println("修改密码操作成功，下次登陆生效。");
    }

    private void exit() {
        System.out.println("谢谢你的使用，期待下次为你服务");
        System.exit(0);
    }
}
